﻿using HostAssistantCore;
using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HostAssistantBLL
{
    /// <summary>
    /// 站点
    /// </summary>
    public class sitebll
    {
        #region 站点列表

      
        public static  List<sitemodel> GetsiteList( string  t="", string txtsname="")
        {
            List<sitemodel> list = new List<sitemodel>();
            Sites Sites = new Sites();
       

            string sql = "  select * from sites where   1=1   ";

            if (!string.IsNullOrWhiteSpace(t))
            {
                sql += "  and sstate=@sstate  ";
                if (t == "启用")
                    Sites.sstate = "Started";
                else
                     if (t == "禁用")
                    Sites.sstate = "Stopped";
                else
                    Sites.sstate = t;

              //  Sites.sstate = t == "启用" ? "Started" : "Stopped";
            }
            if (!string.IsNullOrWhiteSpace(txtsname))
            {
                sql += "  and ( sname like @sname  ";
                Sites.sname = "%"+txtsname.Trim()+ "%" ;


                sql += "  or sbindings like @sbindings ) ";
                Sites.sbindings = "%" + txtsname.Trim() + "%";

                




            }





            var ss = Data<Sites>.GetInstance().GetModelList(sql, Sites);

                

            if(ss!=null)
            {

          

            foreach (var  site in ss)

            {

                if (site.stype != "site")
                    continue;
                  
                sitemodel sitemodel = new sitemodel();
                sitemodel.ID =  site.ID;
                sitemodel.name = site.sname;
                sitemodel.ftpname = site.ftpname;
                sitemodel.binddmoin = site.sbindings;
               
              //  sitemodel.statename = (site.sstate== "Started"? "启用":"禁用");


                string s = "未知";
                if (site.sstate == "Started")
                    s = "启用";
                else
if (site.sstate == "Stopped")
                    s = "禁用";
                sitemodel.statename = s;// (site.sstate == "Started" ? "启用" : "禁用");




                sitemodel.path = site.sphysicalpath;
                string ty = "";
                if(!string.IsNullOrWhiteSpace(site.sphpath))
                {
                    ty = "php";
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(site.snetversion))
                    {
                        ty = "ASP.NET";
                    }
                    else
                    {
                        ty = "其它";
                    }
                }

                sitemodel.type = ty;// !string.IsNullOrWhiteSpace(site.sphpath)?"php": "asp.net";
                sitemodel.v = site.snetversion ;
                sitemodel.typename = sitemodel.type+ sitemodel.v;
                sitemodel.cretime = site.screatetime;
                list.Add(sitemodel);
                  

                NLogger.Fatal(JsonHelper.SerializeObject(site));


            }


            }



            return list;




        
        }
        #endregion

        #region 刷新站点


        public static List<sitemodel> RessiteList()
        {
            List<sitemodel> list = new List<sitemodel>();
             
            var ss = new IISManager().flushSites();



            if(ss!=null)
            {

        

            foreach (var site in ss)

            {
                if (site.stype != "site")
                    continue;

                sitemodel sitemodel = new sitemodel();
                sitemodel.ID = site.ID;
                sitemodel.name = site.sname;
                sitemodel.ftpname = site.ftpname;
                sitemodel.binddmoin = site.sbindings;
                    string s = "未知";
                    if (site.sstate == "Started")
                        s = "启用";
                    else
if (site.sstate == "Stopped")
                        s = "禁用";
                    sitemodel.statename = s;// (site.sstate == "Started" ? "启用" : "禁用");
                sitemodel.path = site.sphysicalpath;
                string ty = "";
                if (!string.IsNullOrWhiteSpace(site.sphpath))
                {
                    ty = "php";
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(site.snetversion))
                    {
                        ty = "ASP.NET";
                    }
                    else
                    {
                        ty = "其它";
                    }
                }


                sitemodel.type = ty;// !string.IsNullOrWhiteSpace(site.snetversion) ? "asp.net" : "";
                sitemodel.v = site.snetversion;
                sitemodel.typename = sitemodel.type + sitemodel.v;
                sitemodel.cretime = site.screatetime;
                list.Add(sitemodel);


                NLogger.Fatal(JsonHelper.SerializeObject(site));


            }

            }




            return list;




          
        }
        #endregion

        #region  是否安装iis

        /// <summary>
        /// 是否安装iis
        /// </summary>
        /// <returns></returns>
        public static bool isiis()
        {





            if (ExistSqlServerService("W3SVC"))
            {
                // MessageBox.Show("IIS已经存在了");
                return true;
            }
            else
            {
                //   MessageBox.Show("IIS没有安装");
                return false;
            }
        }
      

         static bool ExistSqlServerService(string tem)
        {
            bool ExistFlag = false;
            ServiceController[] service = ServiceController.GetServices();
            for (int i = 0; i < service.Length; i++)
            {
                if (service[i].ServiceName.ToString() == tem)
                {
                    ExistFlag = true;
                }
            }
            return ExistFlag;
        }
        #endregion

        #region 安装iis7
        /// <summary>
        /// 安装iis7
        /// </summary>
        public static string InssIIS7()
        {
            string receivePath = System.Windows.Forms.Application.StartupPath + "\\bat\\iis7.bat";
            if (File.Exists(receivePath))
            {
                try
                {


                    ////Process proc = null;

                    ////    string targetDir = System.Windows.Forms.Application.StartupPath + "\\bat\\";// string.Format(@"D:\主机助手\WindowsFormsApp1\bin\Debug\bat\");//this is where testChange.bat lies
                    ////    proc = new Process();
                    ////    proc.StartInfo.WorkingDirectory = targetDir;
                    ////    proc.StartInfo.FileName = "iis7.bat";
                    ////    proc.StartInfo.Arguments = string.Format("10");//this is argument
                    ////                                                   //proc.StartInfo.CreateNoWindow = true;
                    ////                                                   //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                    ////    proc.Start();
                    ////    proc.WaitForExit();



                    ////return "000";
                    Process pro = new Process();
                    FileInfo file = new FileInfo(receivePath);
                    pro.StartInfo.WorkingDirectory = file.Directory.FullName;
                    pro.StartInfo.FileName = receivePath;
                    pro.StartInfo.CreateNoWindow = true;
                    pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    pro.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                    pro.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                    pro.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                    pro.StartInfo.UseShellExecute = false;
                    pro.Start();


                    //  Thread.Sleep(3000);
                    string output = pro.StandardOutput.ReadToEnd();
                    NLogger.Info("安装iis7:" + output);
                    pro.WaitForExit();
                    pro.Close();
                    return output;

                }
                catch (Exception ex)
                {
                    NLogger.Error("Exception Occurred :" + ex.Message + ex.StackTrace.ToString());
                    return ex.Message;
                }


            }

            else
            {
                return "执行文件不存在";
            }
            // Thread.Sleep(3000);
        }

        #endregion

        #region 安装iis8
        /// <summary>
        /// 安装iis8
        /// </summary>
        public static string InssIIS8()
        {
            string receivePath = System.Windows.Forms.Application.StartupPath + "\\bat\\iis8.bat";
            if (File.Exists(receivePath))
            {


                ////Process proc = null;
                ////try
                ////{
                ////    string targetDir = System.Windows.Forms.Application.StartupPath + "/bat/i";// string.Format(@"D:\BizMap\");//this is where testChange.bat lies
                ////    proc = new Process();
                ////    proc.StartInfo.WorkingDirectory = targetDir;
                ////    proc.StartInfo.FileName = "iis8.bat";
                ////    proc.StartInfo.Arguments = string.Format("10");//this is argument
                ////                                                   //proc.StartInfo.CreateNoWindow = true;
                ////                                                   //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                ////    proc.Start();
                ////    proc.WaitForExit();
                ////}
                ////catch (Exception ex)
                ////{
                ////    Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                ////}

                ////return "ok";

                try
                {

                    NLogger.Info("安装iis8 --receivePath:" + receivePath);


                    ////Process proc = null;

                    ////string targetDir = System.Windows.Forms.Application.StartupPath + "\\bat\\";// string.Format(@"D:\主机助手\WindowsFormsApp1\bin\Debug\bat\");//this is where testChange.bat lies
                    ////proc = new Process();
                    ////proc.StartInfo.WorkingDirectory = targetDir;
                    ////proc.StartInfo.FileName = "iis8.bat";
                    ////proc.StartInfo.Arguments = string.Format("10");//this is argument
                    ////                                               proc.StartInfo.CreateNoWindow = true;
                    ////                                             proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                    ////proc.Start();
                    ////proc.WaitForExit();



                    ////return "000";


                    Process pro = new Process();
                    FileInfo file = new FileInfo(receivePath);
                    pro.StartInfo.WorkingDirectory = file.Directory.FullName;
                    pro.StartInfo.FileName = receivePath;
                    pro.StartInfo.CreateNoWindow = true;
                    pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    pro.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                    pro.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                    pro.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                    pro.StartInfo.UseShellExecute = false;
                    pro.Start();


                    //  Thread.Sleep(3000);
                    string output = pro.StandardOutput.ReadToEnd();
                    NLogger.Info("安装iis8:" + output);
                    pro.WaitForExit();
                    pro.Close();
                    return output;

                }
                catch (Exception ex)
                {
                    NLogger.Error("Exception Occurred :" + ex.Message + ex.StackTrace.ToString());
                    return ex.Message;
                }


            }

            else
            {
                return "执行文件不存在";
            }
            // Thread.Sleep(3000);
        }

        #endregion

        #region  获取 站点
        public static Sites GetSites(string id)
        {
            string sql = "    id=@ID  ";
            Sites SqlInfo = new Sites();
            SqlInfo.ID = ZConvert.StrToInt(id);
            return Data<Sites>.GetInstance().GetModel("Sites", sql, SqlInfo);
        }
        #endregion
    }
}